package com.dragon.english_practice_back.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dragon.english_practice_back.entity.Message;
import com.dragon.english_practice_back.entity.User;
import com.dragon.english_practice_back.mapper.MessageMapper;
import com.dragon.english_practice_back.mapper.UserMapper;
import com.dragon.english_practice_back.reponse.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin")
@Slf4j
@PreAuthorize("hasRole('ROLE_ADMIN')")
public class AdminController {

    UserMapper userMapper;
    MessageMapper messageMapper;

    public AdminController(UserMapper userMapper,
                           MessageMapper messageMapper){
        this.userMapper = userMapper;
        this.messageMapper = messageMapper;
    }

    // 获取用户list-分页
    @GetMapping("/getUserList")
    public Result<Page<User>> getUserList(@RequestParam(required = false, defaultValue = "1") Integer page,
                                          @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        Page<User> userPage = new Page<>(page, pageSize);
        userMapper.selectPage(userPage,null);

        return Result.ok("ok",userPage);
    }

    // 修改用户数据
    @PostMapping("/updateUser")
    public Result<String> updateUser(@RequestBody User user){
        user.setPassword(null);
        userMapper.updateById(user);
        return Result.ok("ok");
    }

    // 获取AI消息列表
    @GetMapping("/chatMessages")
    public Result<Page<Message>> getChatMessages(@RequestParam(required = false, defaultValue = "1") Integer page,
                                           @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                                           @RequestParam(required = false) Integer userId){
        Page<Message> page1 = new Page<Message>(page,pageSize);
        Page<Message> selectPage = messageMapper.selectPage(page1, (userId != null && userId >= 1) ? new QueryWrapper<Message>().eq("creator_id", userId) : null);
        return Result.ok("ok",selectPage);
    }

    // 删除所有会话Id为空的消息
    @DeleteMapping("/deleteAllChatMessages")
    public Result<String> deleteAllChatMessages(@RequestParam(required = false) Integer creatorId){
        QueryWrapper<Message> queryWrapper = new QueryWrapper<Message>();

        queryWrapper.isNull("session_id");
        if (creatorId != null && creatorId >= 1){
            queryWrapper.eq("creator_id",creatorId);
        }

        messageMapper.delete(queryWrapper);
        return Result.ok("ok");
    }


}
